package com.wetao.module_pen;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.tstudy.blepenlib.BlePenManager;
import com.tstudy.blepenlib.data.BleDevice;
import com.tstudy.blepenlib.data.CoordinateInfo;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.bean.TabEntity;
import com.wetao.lib_common.contract.EmptyCon;
import com.wetao.lib_common.presenter.EmptyPre;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.DisplayUtil;
import com.wetao.lib_common.utils.FileUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.SPUtils;
import com.wetao.lib_common.utils.StringUtil;
import com.wetao.module_pen.fragment.PenConnectFragment;
import com.wetao.module_pen.fragment.PenSubmitFragment;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;

@Route(path = ConstantArouter.PATH_PEN_PENMAINACTIVITY)
public class PenMainActivity extends BaseActivity<EmptyCon.View, EmptyPre>
        implements EmptyCon.View, PenConnectFragment.OnFragmentInteractionListener, PenSubmitFragment.OnFragmentInteractionListener {
    private static final int HANDLER_INIT_VP_TAB = 1;
    private ViewPager viewPager;
    private CommonTabLayout commonTabLayout;
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private FragmentManager fragmentManager;//声明fragment管理
    private List<Fragment> fragmentList = new ArrayList<>();
    private String[] mTitles = {"未连接", "待提交"};
    private ImageView iv_close;
    PenConnectFragment penConnectFragment;
    PenSubmitFragment penSubmitFragment;
    public static final int REQUEST_CODE_OPEN_GPS = 201;
    public static final int REQUEST_OPEN_BT_CODE = 202;

    private boolean isInitVpTab = false;
    private Badge badge;

    private int mMoudle_temp = TsdService.MODULE_DEFAULT;

    private MyHandler handler;
    static class MyHandler extends Handler {
        WeakReference<PenMainActivity> weakReference;
        public MyHandler(PenMainActivity activity) {
            weakReference = new WeakReference(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if(weakReference.get() == null) {
                return;
            }
            PenMainActivity activity = weakReference.get();
            if(msg.what == HANDLER_INIT_VP_TAB) {
                activity.initVpTab();
                activity.isInitVpTab = true;
            }
        }
    }

    private TsdService.OnDataReceiveListener mTsdListener = new TsdService.OnDataReceiveListener() {
        @Override
        public void onFinish() {
            finish();
        }

        @Override
        public void onErrTsdPen(int code, String msg) {
            if(penConnectFragment != null) {
                penConnectFragment.callErr(code, msg);
            }
        }

        @Override
        public void onRefreshScan(boolean isScaning) {
            if(penConnectFragment != null) {
                penConnectFragment.refreshScan(isScaning);
            }
        }

        @Override
        public void onAddDevice(BleDevice bleDevice) {
            if(penConnectFragment != null) {
                penConnectFragment.addDevice(bleDevice);
            }
        }

        @Override
        public void onPenConnectStatus(int code, BleDevice bleDevice) {
            if(penConnectFragment != null) {
                penConnectFragment.penConnectStatus(code, bleDevice);
            }
        }

        @Override
        public void onGetPenInfo(int batteryPercent, int memoryPercent, int memoryByteNum) {
            if(penConnectFragment != null) {
                penConnectFragment.getPenInfo(batteryPercent, memoryPercent, memoryByteNum);
            }
        }

        @Override
        public void onCoordDraw(CoordinateInfo coordinateInfo) {
            if(penConnectFragment != null) {
                penConnectFragment.onCoordDraw(coordinateInfo);
            }
        }

        @Override
        public void onTeacherExitSmallTest() {

        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.pen_main_activity;
    }

    @Override
    public boolean getIsBindTsdService() {
        return true;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return mTsdListener;
    }

    @Override
    public void setTsdServiceConnected() {
        super.setTsdServiceConnected();
        mMoudle_temp = mTsdServiceBinder.on_getmModule();
    }

    @Override
    public EmptyPre createPresenter() {
        return new EmptyPre(this);
    }

    @Override
    public EmptyCon.View createView() {
        return this;
    }

    @Override
    public void init() {
        DisplayUtil.getScreenRelatedInformation(this);
        DisplayUtil.getRealScreenRelatedInformation(this);
        //禁止息屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        handler = new MyHandler(this);
        //CodeProcessor.init(this);
        //AjLatexMath.init(this); // init library: load fonts, create paint, etc.

        iv_close = findViewById(R.id.iv_close);
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        viewPager = findViewById(R.id.vp);

        commonTabLayout = findViewById(R.id.tl_2);

        handler.sendEmptyMessageDelayed(HANDLER_INIT_VP_TAB, 100);
    }

    @Override
    protected void onDestroy() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        if(handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        super.onDestroy();
    }

    public void initVpTab(){

        penConnectFragment = PenConnectFragment.newInstance();
        penSubmitFragment = PenSubmitFragment.newInstance();
        fragmentList.add(penConnectFragment);
        fragmentList.add(penSubmitFragment);

        fragmentManager = getSupportFragmentManager();

        FragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(fragmentManager);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(fragmentList.size());

        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], 0, 0));
        }

        commonTabLayout.setTabData(mTabEntities);
        commonTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewPager.setCurrentItem(position);

            }

            @Override
            public void onTabReselect(int position) {

            }
        });


        LogUtils.e("tab格式: " + commonTabLayout.getTabCount());
        badge = new QBadgeView(this).bindTarget(commonTabLayout.getChildAt(0));
        badge.setBadgeGravity(Gravity.END | Gravity.TOP );
        badge.setBadgeTextSize(getResources().getDimension(R.dimen.dp_10), false);
        badge.setGravityOffset(getResources().getDimension(R.dimen.dp_100), 0f, false);

    }

    class MyFragmentPagerAdapter extends FragmentPagerAdapter {
        public MyFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }
        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return super.getPageTitle(position);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_OPEN_BT_CODE) {
            if(penConnectFragment == null) {
                return;
            }
            if (resultCode == RESULT_OK ) {
               //penConnectFragment.callErr(TsdService.ERR_TSD_BT_OPEN_T, "蓝牙打开成功");
            } else {
                //penConnectFragment.callErr(TsdService.ERR_TSD_BT_OPEN_F, "蓝牙打开失败");
            }
        }
    }

    private boolean isConnectPen() {
        String penMac = SPUtils.getInstance().getString(Constants.USER_PEN_MAC);
        if(StringUtil.isEmpty(penMac)) {
            return false;
        } else {
            return BlePenManager.getInstance().isConnected(penMac);
        }
    }

    private int noSubmitNum() {
        String studentId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);
        return SPUtils.getInstance().getInt(Constants.USER_PEN_OFFLINE_NOSUBMITNUM + "_" + studentId, 0);
    }

    @Override
    public void on_ct_rePenInit() {
        if(mTsdServiceBinder != null) {
            mTsdServiceBinder.on_rePenInit();
        }
    }

    @Override
    public boolean on_ct_isScaning() {
        if(mTsdServiceBinder != null) {
            return mTsdServiceBinder.on_isScaning();
        }
        return false;
    }

    @Override
    public void on_ct_startScan() {
        if(mTsdServiceBinder != null) {
            mTsdServiceBinder.on_startScan();
        }
    }

    @Override
    public void on_ct_stopScan() {
        if(mTsdServiceBinder != null) {
            mTsdServiceBinder.on_stopScan();
        }
    }
    @Override
    public void on_ct_finishPre() {
        if(mTsdServiceBinder != null) {
            mTsdServiceBinder.on_finishPre();
        }
    }

    @Override
    public void on_ct_penConnect(BleDevice bleDevice) {
        if(mTsdServiceBinder != null) {
            mTsdServiceBinder.on_penConnect(bleDevice);
        }
    }

    @Override
    public BleDevice on_ct_getmBleDevice() {
        if(mTsdServiceBinder != null) {
            return mTsdServiceBinder.on_getmBleDevice();
        }
        return null;
    }

    @Override
    public void on_ct_switchTab() {
        viewPager.setCurrentItem(1);
        commonTabLayout.setCurrentTab(1);
        if(penSubmitFragment != null) {
            penSubmitFragment.reLoadData();
        }
    }

    @Override
    public void on_ct_setmMoudle(int module) {
        if(mTsdServiceBinder != null) {
            if(module == TsdService.MODULE_DEFAULT) {
                mTsdServiceBinder.on_setmModule(mMoudle_temp);
            } else {
                mTsdServiceBinder.on_setmModule(module);
            }
        }
    }

    @Override
    public int on_ct_getmMoudle() {
        if(mTsdServiceBinder != null) {
            return mTsdServiceBinder.on_getmModule();
        }
        return TsdService.MODULE_DEFAULT;
    }

    @Override
    public void on_ct_setIsConnect(boolean isConnect) {
        if(isConnect) {
            mTitles[0] = "已连接";
        } else {
            mTitles[0] = "未连接";
        }
        if(isInitVpTab) {
            commonTabLayout.getTitleView(0).setText(mTitles[0]);
        }
    }

    @Override
    public void on_st_setNoSubmitNum(int count) {
        badge.setBadgeNumber(count);
    }
}
